const Router = require("koa-router")
const {successRender, errorRender, paginationFilter, generateOrderId} = require('../utils/utils')
const router = new Router()
const Recharge = require('../model/Recharge')
const User = require('../model/User')
const {proving} = require('../utils/token')

//查询充值列表
router.get('/getRechargeList', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  const keyWord = ctx.request.query.keyWord
  if (userId) {
    let res
    if (keyWord) {
      res = await Recharge.find({oddId: keyWord})
    } else {
      res = await Recharge.find()
    }
    const data = paginationFilter(res, ctx.request.query)
    ctx.body = successRender({data})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//充值申请
router.post('/addRecharge', async ctx => {
  const recharge = ctx.request.body
  const token = ctx.request.header.token
  const userInfo = await User.find({openId: proving(token).id})
  if (recharge.password !== userInfo[0].password) return ctx.body = errorRender({msg: '密码错误'})
  recharge.userId = proving(token).id
  recharge.oddId = generateOrderId(5)
  recharge.nickName = userInfo[0].nickName
  const res1 = await new Recharge(recharge).save()
  userInfo[0].money = userInfo[0].money + recharge.money
  const res2 = await User.findByIdAndUpdate(userInfo[0]._id, userInfo[0])
  ctx.body = successRender({msg: '充值成功!'})
})

//删除订单
router.get('/removeRecharge', async ctx => {
  const token = ctx.request.header.token
  const _id = ctx.request.query.id
  const userId = proving(token).id
  if (userId) {
    const res = await Recharge.findOneAndRemove({_id})
    ctx.body = successRender({msg: '删除成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//审核
router.post('/examine', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  if (userId) {
    const id = ctx.request.body._id
    const info = ctx.request.body
    const res = await Recharge.findByIdAndUpdate(id, info)
    ctx.body = successRender({msg: '审核成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})


module.exports = router
